/*
 * @Author: PC-202208041440\Administrator 1412395843@qq.com
 * @Date: 2022-08-10 09:47:34
 * @LastEditors: code-shan
 * @LastEditTime: 2023-03-10 11:44:27
 * @FilePath: \question-bank-admin\src\utils\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import config from '@/config/config'
// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  // baseURL: process.env.VUE_APP_API_BASE_URL,
  baseURL: config.baseUrl,
  // baseURL: 'http://192.168.2.179:8000',
  timeout: 1000 * 60 * 2, // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      if (data.status === '401') {
        notification.error({ message: '403提示', description: '登录信息过期，请重新登录' })
        if (token) {
          store.dispatch('Logout').then(() => {
            setTimeout(() => {
              window.location.reload()
            }, 1500)
          })
        }
      } else {
        notification.error({ message: '403提示', description: data.detail })
      }
    }
    if ([400, 405].includes(error.response.status)) {
      notification.error({ message: '错误提示', description: data.detail })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({ message: '401提示', description: '登录信息过期，请重新登录' })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
    if (error.response.status === 499) {
      notification.error({ message: '错误提示', description: data.detail })
    }
  }
  return Promise.reject(error)
}

request.interceptors.request.use((config) => {
  const token = storage.get(ACCESS_TOKEN)
  if (token) {
    config.headers['token'] = token
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  if (![200, 201, 204].includes(response.status)) {
    notification.error({
      message: '请求失败',
      description: `错误信息原因：${response.data.detail || '未知错误'}`,
    })
  }
  return response.data
}, errorHandler)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  },
}

export default request

export { installer as VueAxios, request as axios }
